<template>
  <full-dialog :visible.sync="visible" :fullscreen.sync="fullscreen" title="人员选择" width="80%" @closed="reset" class="user-dialog">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="6" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"/>
        </div>
        <div class="head-container dept-tree">
          <el-tree
            v-loading="treeLoading"
            :props="defaultProps"
            :data="treeDeptData"
            node-key="id"
            :expand-on-click-node="false"
            :default-expanded-keys="treeExpandData"
            :filter-node-method="filterNode"
            highlight-current
            ref="tree"
            @node-click="handleNodeClick"/>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="18" :xs="24" class="user-table">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="用户工号" prop="loginName">
            <el-input
              v-model="queryParams.loginName"
              placeholder="请输入用户工号"
              clearable
              size="small"
              style="width: 200px"
              @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="用户名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 200px"
              @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              size="small"
              style="width: 200px">
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table ref="multipleTable" v-loading="table.loading" :data="table.data"
                  @selection-change="handleSelectionChange" @select="handleSelect" @select-all="handleSelectAll">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="用户工号" align="center" key="loginName" prop="loginName"/>
          <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true"/>
          <el-table-column label="性别" align="center" key="sexName" prop="sexName"/>
          <el-table-column label="所属组织" align="center" key="orgName" prop="orgName" :show-overflow-tooltip="true"/>
          <el-table-column label="所属部门" align="center" key="deptName" prop="deptName" :show-overflow-tooltip="true"/>
          <el-table-column label="岗位" align="center" key="postName" prop="postName" width="120"/>
          <el-table-column label="状态" align="center" key="status">
            <template slot-scope="scope">
              <status-tag :status-options="statusOptions" :status="scope.row.status"></status-tag>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="page.total > 0"
          :total="page.total"
          :page.sync="page.current"
          :limit.sync="page.size"
          @pagination="initUserList"/>

        <el-form :model="userForm" :rules="rules" ref="userForm" :inline="true" label-width="80px" class="selected-user-form">
          <el-form-item label="已选人员" prop="selections">
            <div style="min-width: 200px;min-height: 8px">
              <el-tag v-for="(item, index) in userForm.selections" :key="item.code" closable @close="handleClose(index)" class="user-tag">{{ item.name }}</el-tag>
            </div>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="select">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </div>
  </full-dialog>
</template>

<script>
import { listUser } from "@/api/system/user";
import { deptTree } from "@/api/system/dept";

export default {
  name: "UserTable",
  props: {
    multipleMode: {
      type: Boolean,
      default: true
    }
  },
  data() {
    const validateUsers = (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('请至少选择一个人员'));
        return;
      }

      // 非多选模式
      if (!this.multipleMode) {
        if (value.length > 1) {
          callback(new Error('只能选择一个人员'));
          return;
        }
      }
      callback();
    };

    return {
      visible: false,
      fullscreen: true,
      // 部门名称
      deptName: undefined,
      treeLoading: false,
      treeDeptData: [],
      treeExpandData:[],
      statusOptions: [],
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: 'leaf'
      },
      // 查询参数
      queryParams: {
        loginName: undefined,
        userName: undefined,
        status: undefined,
        orgId: undefined,
        deptId: undefined
      },
      table: {
        data: [],
        loading: false,
      },
      page: {
        total: 0,
        current: 1,
        size: 10,
      },
      userForm: {
        // 选中数组
        selections: [],
      },
      // 表单校验
      rules: {
        selections: [
          { validator: validateUsers, trigger: 'change' }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    init(selections) {
      this.visible = true;
      this.userForm.selections = selections;
      this.initDeptTree();
      this.initUserList();
      this.getDicts("sys_user_status").then(res => {
        this.statusOptions = res;
      })
    },
    initDeptTree() {
      this.treeLoading = true;
      deptTree().then(res => {
        this.treeLoading = false;

        this.treeDeptData = res;
        this.$lodash.forEach(res, item => {
          this.treeExpandData.push(item.id);
        });
      }).catch(() => {
        this.treeLoading = false;
      });
    },
    /** 查询用户列表 */
    initUserList() {
      this.table.loading = true;
      listUser({
        loginName: this.queryParams.loginName,
        userName: this.queryParams.userName,
        status: this.queryParams.status,
        orgId: this.queryParams.orgId,
        deptId: this.queryParams.deptId,
        page: true,
        current: this.page.current,
        size: this.page.size,
      }).then(response => {
        this.table.data = response.records;
        this.page.total = response.total;
        this.table.loading = false;

        this.$nextTick(() => {
          this.toggleSelection();
        });
      }).catch(() => {
        this.table.loading = false;
      });
    },
    toggleSelection() {
      this.$refs.multipleTable.clearSelection();

      this.$lodash.forEach(this.table.data, item => {
        this.$lodash.forEach(this.userForm.selections, row => {
          if (row.code === item.loginName) {
            this.$refs.multipleTable.toggleRowSelection(item, true);
          }
        });
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) {
        return true;
      }
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (data.bzflag === "Z") {
        this.queryParams.orgId = data.id;
        this.queryParams.deptId = undefined;
      } else {
        this.queryParams.orgId = undefined;
        this.queryParams.deptId = data.id;
      }
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.page.current = 1;
      this.initUserList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.tree.setCurrentKey(null);
      this.resetForm("queryForm");
      this.queryParams.orgId = undefined;
      this.queryParams.deptId = undefined;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.$lodash.each(selection, item => {
        const users = this.$lodash.filter(this.userForm.selections, function(o) { return o.code === item.loginName; });
        if (!users || users.length === 0) {
          item.code = item.loginName;
          item.name = item.userName;
          this.userForm.selections.push(item);
        }
      });
    },
    handleSelect(selection, row) {
      const users = this.$lodash.filter(selection, function(o) { return o.loginName === row.loginName; });
      // 如果不在里面，说明是取消勾选的
      if (!users || users.length === 0) {
        const index = this.$lodash.findIndex(this.userForm.selections, function(o) { return o.code === row.loginName; });
        this.spliceData(index, false);
      }
    },
    handleSelectAll(selection) {
      // 取消全选
      if (!selection || selection.length === 0) {
        this.$lodash.forEach(this.table.data, row => {
          const index = this.$lodash.findIndex(this.userForm.selections, function(o) { return o.code === row.loginName; });
          this.spliceData(index, false);
        });
      }
    },
    handleClose(index) {
      this.spliceData(index, true);
    },
    spliceData(index, changeCheck) {
      if (changeCheck) {
        const user = this.userForm.selections[index];
        const row = this.$lodash.find(this.table.data, function(o) { return o.loginName === user.code; });
        this.$refs.multipleTable.toggleRowSelection(row, false);
      }
      this.userForm.selections.splice(index, 1);
    },
    select() {
      this.$refs["userForm"].validate(valid => {
        if (valid) {
          this.$emit("set-value", this.userForm.selections);
          this.close();
        }
      });
    },
    close() {
      this.visible = false;
    },
    // 表单重置
    reset() {
      this.deptName = undefined;
      this.userForm.selections = [];
      this.resetForm("queryForm");
      this.resetForm("userForm");
    }
  }
};
</script>

<style lang="scss" scoped>
  .dept-tree {
    height: 78vh;
    overflow: auto;
    & ::v-deep .el-tree {
      display: inline-block;
    }

    & ::v-deep .el-tree__empty-text {
      display: contents;
    }
  }

  .user-dialog {
    & ::v-deep .el-dialog__body {
      padding-bottom: 0;
    }
  }

  .selected-user-form {
    margin-top: 20px;
  }

  .user-tag {
    margin-right: 8px;
  }
</style>
